package com.zetyun.tiger.format.date.compact.gbism;

import com.zetyun.rt.meta.annotation.ActionMeta;
import com.zetyun.rt.sdk.action.MapAction;
import com.zetyun.rt.sdk.model.RtEvent;
import com.zetyun.rt.sdk.operator.OperatorContext;
import com.zetyun.tiger.format.date.SpecialDateFormatUtil;
import com.zetyun.tiger.format.date.compact.SimpleDateFormatParameter;

import java.util.Map;
import java.util.Objects;

import static com.zetyun.tiger.format.date.FormatConstant.*;


@ActionMeta(
        id = "tiger.gbism-date-format",
        tags = {"formatter"},
        category = "map",
        name = "GbismDateFormat",
        parameterClass = GBISMDateFormatParameter.class,
        status = ActionMeta.Status.PUBLIC,
        description = "Gbism系统 表统一日期格式"
)
public class GbismDateFormatAction extends MapAction {

    private Map<String, GbismDataFormatTuple> mapping;

    @Override
    public void init(OperatorContext context) {
        super.init(context);
        GBISMDateFormatParameter parameters = context.getParameters();
        mapping = parameters.toMapping();


    }

    @Override
    public RtEvent apply(RtEvent in) throws Exception {

        // 获取目标主题名称
        String sinTopic = in.getHeader(SINK_TOPIC, String.class);

        // 根据目标主题名称寻找格式化信息
        GbismDataFormatTuple formatTuple = mapping.get(sinTopic);

        // 根据格式化Tuple寻找日期字段 O(1)
        String dateField = formatTuple.getDateField();

        // 根据格式化Tuple寻找交易时间字段 O(1)
        String trxTimeField = formatTuple.getTrxTimeField();

        // 根据格式化Tuple寻找结束时间字段 O(1)
        String endTimeField = formatTuple.getEndTimeField();

        long procTs = System.currentTimeMillis();
        String currentSystemDate = SpecialDateFormatUtil.toYmdHms(procTs);
        in.setField(RT_PROC_TMS, procTs);
        in.setField(RT_PROC_TIME, currentSystemDate);

        Object dateObject = in.getField(dateField);
        if (Objects.nonNull(dateObject) && !dateObject.toString().isEmpty()) {
            Object trxField = in.getField(trxTimeField);
            if (Objects.nonNull(trxField) && !trxField.toString().isEmpty()) {
                Long dataTs = SpecialDateFormatUtil.toGbismTs(
                        dateObject.toString(),
                        trxField.toString(),
                        in.getField(endTimeField)
                );
                String formatDate = SpecialDateFormatUtil.toYmdHms(dataTs);
                in.setField(RT_EVENT_TMS, dataTs);
                in.setField(RT_EVENT_TIME, formatDate);
            } else {
                in.setField(RT_EVENT_TMS, procTs);
                in.setField(RT_EVENT_TIME, currentSystemDate);
            }
        } else {
            in.setField(RT_EVENT_TMS, procTs);
            in.setField(RT_EVENT_TIME, currentSystemDate);
        }

        in.setField(RT_EVENT_TYPE, in.getField("op_"));
        in.removeField("op_");
        return in;
    }
}
